package com.sky.orangehireserver.modules.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.orangehireserver.common.domain.Users;
import com.sky.orangehireserver.common.service.UsersService;
import com.sky.orangehireserver.enums.UserRoleEnum;
import com.sky.orangehireserver.exception.BizException;
import com.sky.orangehireserver.modules.admin.dto.AdminLoginDTO;
import com.sky.orangehireserver.modules.admin.service.AdminAuthService;
import com.sky.orangehireserver.modules.admin.vo.AdminAccountVO;
import com.sky.orangehireserver.modules.admin.vo.AdminLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;



@Slf4j
@Service
@RequiredArgsConstructor
public class AdminAuthServiceImpl implements AdminAuthService {
    private final UsersService usersService;
    // Token过期时间（2小时）
    private static final long TOKEN_EXPIRE_TIME = 2 * 60 * 60 * 1000;
    /**
     * @description 超级管理员登录;
     * @param loginDTO 登录请求DTO
     * @return AdminLoginVO
     */
    @Override
    public AdminLoginVO login(AdminLoginDTO loginDTO) {
        log.info("求职者登录，邮箱：{}", loginDTO.getEmail());

        // 查找用户
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getEmail, loginDTO.getEmail())
                .eq(Users::getRole, UserRoleEnum.SUPER_ADMIN.getCode());

        Users user = usersService.getOne(queryWrapper);
        if (user == null) {
            throw new BizException("USER_NOT_FOUND", "用户不存在或邮箱错误");
        }

        // 检查用户状态
        if (!"active".equals(user.getStatus())) {
            throw new BizException("USER_INACTIVE", "用户账号已被禁用");
        }

        // 验证密码
        if (!BCrypt.checkpw(loginDTO.getPassword(), user.getPasswordHash())) {
            throw new BizException("PASSWORD_ERROR", "密码错误");
        }


        // 使用SaToken生成token 访问令牌;
        StpUtil.login(user.getId());
        String accessToken =StpUtil.getTokenValue();
        log.info("求职者登录成功，用户ID：{}", user.getId());

        return AdminLoginVO.builder()
                .accessToken(accessToken)
                .tokenType("Bearer")
                .expiresIn(TOKEN_EXPIRE_TIME / 1000)
                .userInfo(convertToVO(user))
                .build();
    }
    private AdminAccountVO convertToVO(Users user) {
        AdminAccountVO vo = BeanUtil.copyProperties(user, AdminAccountVO.class);

        // 设置角色名称
        UserRoleEnum roleEnum = UserRoleEnum.getByCode(user.getRole());
        if (roleEnum != null) {
            vo.setRoleName(roleEnum.getName());
        }

        return vo;
    }
}
